import { useMenuStore } from "@/stores/menu";
import { useTabsStore } from "@/stores/tabs";
import { isNavigationFailure, NavigationHookAfter, Router } from "vue-router";
import { getExactMatched } from "../routes/helpers";

const tabsHook: NavigationHookAfter = function (to, from, failure) {
  if (isNavigationFailure(failure)) return;

  const tabsStore = useTabsStore();
  const menuStore = useMenuStore();
  const exactMatched = getExactMatched(to.matched);
  if (to.meta.title && !exactMatched.children.length) {
    const tabLabel = to.meta.title;
    const fullPath = to.fullPath;
    tabsStore.addTabByRoute(to);
    tabsStore.setActiveTab(tabLabel);
    menuStore.setActiveMenu(fullPath);
  }
};

export default function createTabsHook(router: Router) {
  router.afterEach(tabsHook);
}
